/*
    This file is part of Raptor.

    Raptor is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Raptor is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Raptor.  If not, see <http://www.gnu.org/licenses/>.

 */

#include <QString>
#include <QStringList>
#include <QPair>

QStringList sizeNames = QStringList() << "B" << "KB" << "MB" << "GB" << "TB";
QStringList speedNames = QStringList() << "B/s" << "KB/s" << "MB/s" << "GB/s" << "TB/s";

QString getLeadingZero(const int &i)//fuellt 2stellinge zahlen auf 1 -> 01, 10 -> 10
{
	if(i < 10)
		return QString("0%1").arg(i);
	else
		return QString("%1").arg(i);
}

QString getTimeString(const int &sec)
{
	int hs = (int)(sec / 3600);
	int mins = (int)((sec % 3600) / 60);
	int secs = (int)((sec % 3600) % 60);

	if(hs == 0)
	{
		if(mins == 0)
		{
			return QString("%1 s").arg(secs);
		} else
		{
			return QString("%1:%2").arg(mins).arg(getLeadingZero(secs));
		}
	} else
	{
		return QString("%1:%2:%3").arg(hs).arg(getLeadingZero(mins)).arg(getLeadingZero(secs));
	}
}

QString transformToString(const quint64 &got)
{
	double size = got;
	int mega = 0;

	while(size > 1024)
	{
		size = size / 1024;
		++mega;
	}

	return QString("%L1 ").arg(size, 0, 'g', 3) + sizeNames.at(mega);
}

QString getSizeString(const quint64 &got, const quint64 &size)
{
	return transformToString(got) + " / " + transformToString(size);
}

QString getSizeString(const quint64 &size)
{
	return transformToString(size);
}

quint64 transformFromString(const QString &str)
{
	QStringList tmpStrList = str.split(" ");

	quint64 size = quint64(tmpStrList.at(0).trimmed().toDouble());

	for(int i=0; tmpStrList.size() == 2 && tmpStrList.at(1).trimmed() != "Bytes" && i<sizeNames.size(); ++i)
	{
		if(tmpStrList.at(1).trimmed() == sizeNames.at(i)) break;

		size = size * 1024;
	}

	return size;
}

QPair<quint64, quint64> getSizeFromString(const QString &str)
{
	QPair<quint64, quint64> tmpReturn;// = qMakePair(0, 0);
	tmpReturn.first = 0;
	tmpReturn.second = 0;

	QStringList tmpStrList = str.split("/");

	if(tmpStrList.size() == 2)
	{
		tmpReturn.first = transformFromString(tmpStrList.at(0).trimmed());
		tmpReturn.second = transformFromString(tmpStrList.at(1).trimmed());
	}

	return tmpReturn;
}


QString getSpeedString(const double &bps)
{
	if(bps == 0) return "-";

	int mega = 0;
	double speed = bps;

	while(speed > 1024)
	{
		speed = speed / 1024;
		++mega;
	}

	return QString("%L1 ").arg(speed, 0, 'g', 3) + speedNames.at(mega);
}
